/**
 * Organizations 模块 API
 * 组织管理相关接口
 */

import { request, type ApiResponse } from "../request";

// ============ 类型定义 ============

/**
 * 组织信息
 */
export interface Organization {
	id: string;
	slug: string;
	name: string;
}

/**
 * 组织详情
 */
export interface OrganizationDetail {
	id: string;
	name: string;
	plan?: "free" | "pro" | "team" | "enterprise";
	opt_in_tags: string[];
	allowed_release_channels: string[];
}

/**
 * 组织成员
 */
export interface OrganizationMember {
	user_id: string;
	user_name: string;
	email?: string;
	role_name: string;
	mfa_enabled: boolean;
}

/**
 * 创建组织请求
 */
export interface CreateOrganizationBody {
	name: string;
}

/**
 * 项目认领预览
 */
export interface ProjectClaimPreview {
	project: {
		ref: string;
		name: string;
	};
	preview: {
		valid: boolean;
		warnings: Array<{ key: string; message: string }>;
		errors: Array<{ key: string; message: string }>;
		info: Array<{ key: string; message: string }>;
		members_exceeding_free_project_limit: Array<{ name: string; limit: number }>;
		source_subscription_plan: "free" | "pro" | "team" | "enterprise";
		target_subscription_plan: "free" | "pro" | "team" | "enterprise" | null;
	};
	expires_at: string;
	created_at: string;
	created_by: string;
}

// ============ API 方法 ============

/**
 * 获取所有组织列表
 */
export function listOrganizations(): Promise<ApiResponse<Organization[]>> {
	return request.get<Organization[]>("/v1/organizations");
}

/**
 * 创建组织
 */
export function createOrganization(
	data: CreateOrganizationBody
): Promise<ApiResponse<Organization>> {
	return request.post<Organization>("/v1/organizations", data);
}

/**
 * 获取组织详情
 */
export function getOrganization(slug: string): Promise<ApiResponse<OrganizationDetail>> {
	return request.get<OrganizationDetail>(`/v1/organizations/${slug}`);
}

/**
 * 获取组织成员列表
 */
export function listOrganizationMembers(
	slug: string
): Promise<ApiResponse<OrganizationMember[]>> {
	return request.get<OrganizationMember[]>(`/v1/organizations/${slug}/members`);
}

/**
 * 获取项目认领详情
 */
export function getProjectClaim(
	slug: string,
	token: string
): Promise<ApiResponse<ProjectClaimPreview>> {
	return request.get<ProjectClaimPreview>(
		`/v1/organizations/${slug}/project-claim/${token}`
	);
}

/**
 * 认领项目
 */
export function claimProject(
	slug: string,
	token: string
): Promise<ApiResponse<Record<string, never>>> {
	return request.post<Record<string, never>>(
		`/v1/organizations/${slug}/project-claim/${token}`
	);
}

export default {
	listOrganizations,
	createOrganization,
	getOrganization,
	listOrganizationMembers,
	getProjectClaim,
	claimProject
};
